package com.jwt.boot.interceptors;

import com.jwt.boot.utils.JWTUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 实现自己的拦截器
 * @date 2020/10/4 14:36
 */
@Slf4j
public class JWTInterceptors implements HandlerInterceptor {



    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 获取请求头中的令牌
        String token = request.getHeader("token");


//        验证令牌
        try {
            Claims claim = JWTUtil.getClaimByToken(token);
            if (!StringUtils.isEmpty(claim)){
                return true;
            }else {
                log.error("验证失败，请重新登录");
                return false;
            }
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }
}
